<?php defined('SYSPATH') OR die('No direct access allowed.');
/**
 * Menangani home
 * @author petra.barus
 */
class Problems_Controller extends Template_Controller {
    protected $restrict_guest = FALSE;
    public $use_template = TRUE;

    /**
     * Menampilkan index
     */
    public function index()
    {
        $this->body->problems = Problem_Model::get_list();
        $this->title = "Problems";
    }

    /**
     *
     * @param string $token
     */
    public function view($token)
    {
        $problem = new Problem_Model($token);
        $this->renderer = url::site('problems/render_viewfile/'.$token);
        $this->title = $problem->get_property('title');
        $this->body->problem = $problem;
    }

    public function submit($token)
    {
        $problem = new Problem_Model($token);
        $submission = new Submission_Model();
        $submission->problem = $problem;
        $submission->submit_time = date("Y-m-d H:i:s");
        $submission->save();

        //TODO:
        $retval = ProblemController::submit_submission($submission);
        if ($retval)
        {
            $submission->save();
            Dispatcher::dispatch($submission);
            exit;
            $this->redirect(url::site('problems/view/'.$problem->token).'#submit_tab', "Submit success", "Your answer has been submitted");
        }
        else
        {
            $submission->delete();
            $this->redirect(request::referrer(), 'submit failed', 'Submit failed');
        }
        exit;
    }

    /**
     *
     */
    public function upload()
    {
        if ($_POST)
        {
            $filepath = "";
            Packager::unpack($filepath);
        }
    }

    public function render_viewfile($token)
    {
        $problem = new Problem_Model($token);
        if (!isset($_GET['file']))
        {
            exit;
        }
        $filename = $_GET['file'];
        ProblemController::render_view_file($problem, $filename);
        exit;
    }
}
//end of file